package abacab.remote.ref;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import abacab.ref.ActorRef;
import abacab.remote.Connection;
import abacab.remote.message.Message;

/**
 * Represents a remote actor's reference
 * 
 * @param <M>
 *          the type of messages handled by the actor(s)
 */
public class RemoteActorRef<M> implements ActorRef<M> {
	/** The logger */
	private static final Logger	logger	= LoggerFactory.getLogger(RemoteActorRef.class);

	/** The path */
	private final String				path;

	/** The connection */
	private volatile Connection	connection;

	/**
	 * Create the reference
	 * 
	 * @param path
	 *          the path
	 * @param connection
	 *          the connection
	 */
	public RemoteActorRef(String path, Connection connection) {
		this.path = path;
		this.connection = connection;
	}

	/**
	 * Set the connection
	 * 
	 * @param connection
	 *          the connection
	 */
	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	@Override
	public String getPath() {
		return this.path;
	}

	@Override
	public void stop() {
		throw new IllegalStateException("Can not stop a remote actor");
	}

	@Override
	public <N> void send(M message, ActorRef<N> sender) {
		if (this.connection != null) {
			try {
				this.connection.send(new Message(sender, this, message));
			}
			catch (IOException e) {
				// TODO: handle the error correctly
				logger.error("Failed to send a message");
			}
		}
	}
}